package com.estar.assistsurvy.activity;

import java.util.ArrayList;
import java.util.List;

import com.estar.assistsurvy.R;
import com.estar.assistsurvy.adapter.MessageTypeListAdapter;
import com.estar.assistsurvy.adapter.TaskSuperviseAdapter;
import com.estar.assistsurvy.entity.RequestOthers;
import com.estar.assistsurvy.entity.RequestTask;
import com.estar.assistsurvy.entity.ResponseOrder;
import com.estar.assistsurvy.thread.GetOtherThread;
import com.estar.assistsurvy.thread.TaskSupervisionThread;
import com.estar.assistsurvy.entity.grabList;
import com.estar.assistsurvy.entity.grabPersonLocation;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.MightypleUtil;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class TaskSuperviseActivity extends BaseActivity implements OnRefreshListener,OnClickListener,OnItemClickListener{

	private TextView caseNumber,targetCar,taskState,sstime;
	private LinearLayout returnHome;
	private Intent intent;
	private String uuid,deviceId,car="",task="",state="",sTime="",eTime="";;
	private SharedPreferences preference;
	private List<grabList> grbaList;
	private SwipeRefreshLayout mSwipeLayout;
	private ListView mListView;
	private TaskSuperviseAdapter adapter;
	private grabList order;
	private ProgressDialog dialog;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(dialog!=null){
				dialog.dismiss();
			}
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;
				
			case 0:
				ResponseOrder task=new ResponseOrder();
				task=(ResponseOrder) msg.obj;
				showShortToast(task.getMessages());
				if(task.getCode().equals("1")){
					grbaList=new ArrayList<grabList>();
					if(task.getGrabList()!=null&&task.getGrabList().size()!=0){
						grbaList=task.getGrabList();
//						for(int i=0;i<task.getGrabList().length;i++){
//							grbaList.add(task.getGrabList()[i]);
//						}
						
					}else{
						showShortToast("当前搜索结果为空!");
					}
					
				}else if(task.getCode().equals("2")){
					ExitUtils.Unlogin(TaskSuperviseActivity.this, task.getMessages());
				}
				if(grbaList.size()==0){
					showShortToast("当前搜索结果为空!");
				}
				adapter=new TaskSuperviseAdapter(grbaList, TaskSuperviseActivity.this);
				mListView.setAdapter(adapter);
				mSwipeLayout.setRefreshing(false);
				break;
				
			case 1:
				grabPersonLocation PersonLocation=new grabPersonLocation();
				PersonLocation=(grabPersonLocation) msg.obj;
				if(PersonLocation.getCode().equals("1")){
					intent=new Intent(TaskSuperviseActivity.this, OrderDetailActivity.class);
					intent.putExtra("order", order);
					intent.putExtra("location", PersonLocation);
					startActivity(intent);
				}else if(PersonLocation.getCode().equals("2")){
					ExitUtils.Unlogin(TaskSuperviseActivity.this, PersonLocation.getMessages());

				}
				break;

			default:
				break;
			}
		};
	};
	
	private AlertDialog.Builder builder;
	private LayoutInflater inflater;
	private View dialogView;
	private ListView select_messageType;
	private ArrayList<String> list;
	private MessageTypeListAdapter stateAdapter;
	private String[] states=new String[]{"全部","未抢单","抢单终止","已抢单","放弃抢单","注销","已完成"};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tasksupervise);

		initView();

	}

	@SuppressWarnings("deprecation")
	private void initView(){
		returnHome=find(R.id.returnBack);
		returnHome.setOnClickListener(this);
		caseNumber=find(R.id.caseNumber);
		caseNumber.setOnClickListener(this);
		targetCar=find(R.id.targetCar);
		targetCar.setOnClickListener(this);
		taskState=find(R.id.taskState);
		taskState.setOnClickListener(this);
		sstime=find(R.id.sstime);
		sstime.setOnClickListener(this);

		mListView = (ListView) findViewById(R.id.id_listview);
		mListView.setDividerHeight(12);
		mListView.setOnItemClickListener(this);
		mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);

		mSwipeLayout.setOnRefreshListener(this);
		mSwipeLayout.setColorScheme(android.R.color.holo_green_dark, android.R.color.holo_green_light,
				android.R.color.holo_orange_light, android.R.color.holo_red_light);
		//		mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDatas);
		//		mListView.setAdapter(mAdapter);
		mSwipeLayout.setRefreshing(true);
		
		preference=getSharedPreferences("user", Context.MODE_PRIVATE);
		uuid=preference.getString("uuid", "");
		deviceId=MightypleUtil.getDeviceId(this);
		initList();
	}

	private void initList(){
		dialog=ProgressDialog.show(this, null, "获取监管列表", false, true);
		RequestTask requestTask=new RequestTask(deviceId, uuid, task, car, state, sTime, eTime);
		new TaskSupervisionThread(TaskSuperviseActivity.this, handler, requestTask).start();
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		initList();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.returnBack:
			finish();
			break;

		case R.id.caseNumber:
			intent=new Intent(TaskSuperviseActivity.this, SearchCaseActivity.class);
//			intent.putExtra("key", 0);
			startActivityForResult(intent, 0);
			break;

		case R.id.targetCar:
			intent=new Intent(TaskSuperviseActivity.this, SearchTargetcarActivity.class);
//			intent.putExtra("key", 1);
			startActivityForResult(intent, 1);
			break;

		case R.id.taskState:
//			intent=new Intent(TaskSuperviseActivity.this, SearchStateActivity.class);
//			startActivityForResult(intent, 2);
			inflater=LayoutInflater.from(TaskSuperviseActivity.this);
			dialogView=inflater.inflate(R.layout.messagetype_layout, null);
			select_messageType=(ListView) dialogView.findViewById(R.id.select_messageType);
			list=new ArrayList<>();
			for(int i=0;i<states.length;i++){
				list.add(states[i]);
			}
			stateAdapter=new MessageTypeListAdapter(list, TaskSuperviseActivity.this);
			select_messageType.setAdapter(stateAdapter);
			preference=getSharedPreferences("taskState", MODE_PRIVATE);
			final Editor editor=preference.edit();
			int messagetype=preference.getInt("taskState", -1);
			if(messagetype!=-1){
				stateAdapter.setSelectItem(messagetype);
				stateAdapter.notifyDataSetChanged();
			}else {
				stateAdapter.setSelectItem(0);
				stateAdapter.notifyDataSetChanged();
			}
			
			builder=new AlertDialog.Builder(TaskSuperviseActivity.this, AlertDialog.THEME_HOLO_LIGHT)
			.setView(dialogView);
			final AlertDialog dialog=builder.create();
			Window dialogWindow=dialog.getWindow();
			WindowManager.LayoutParams params=dialogWindow.getAttributes();
			dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);

	        /*
	         * lp.x与lp.y表示相对于原始位置的偏移.
	         * 当参数值包含Gravity.LEFT时,对话框出现在左边,所以lp.x就表示相对左边的偏移,负值忽略.
	         * 当参数值包含Gravity.RIGHT时,对话框出现在右边,所以lp.x就表示相对右边的偏移,负值忽略.
	         * 当参数值包含Gravity.TOP时,对话框出现在上边,所以lp.y就表示相对上边的偏移,负值忽略.
	         * 当参数值包含Gravity.BOTTOM时,对话框出现在下边,所以lp.y就表示相对下边的偏移,负值忽略.
	         * 当参数值包含Gravity.CENTER_HORIZONTAL时
	         * ,对话框水平居中,所以lp.x就表示在水平居中的位置移动lp.x像素,正值向右移动,负值向左移动.
	         * 当参数值包含Gravity.CENTER_VERTICAL时
	         * ,对话框垂直居中,所以lp.y就表示在垂直居中的位置移动lp.y像素,正值向右移动,负值向左移动.
	         * gravity的默认值为Gravity.CENTER,即Gravity.CENTER_HORIZONTAL |
	         * Gravity.CENTER_VERTICAL.
	         */
			params.x = 100; // 新位置X坐标
			params.y = 180; // 新位置Y坐标
			params.width = 140; // 宽度
			params.height = 120; // 高度
			params.alpha = 0.9f; // 透明度

	        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
	        // dialog.onWindowAttributesChanged(lp);
	        dialogWindow.setAttributes(params);
			dialog.show();
			select_messageType.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					// TODO Auto-generated method stub
					stateAdapter.setSelectItem(position);
					adapter.notifyDataSetChanged();
					
					editor.putInt("taskState", position);
					editor.commit();
					if(position==0){
						state="";
					}else{
						state=String.valueOf(position);
					}
					initList();
					dialog.dismiss();
					dialog.cancel();
				}
			});
			break;

		case R.id.sstime:
			intent=new Intent(TaskSuperviseActivity.this, SearchTimeActivity.class);
			startActivityForResult(intent, 3);
			break;

		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		preference=getSharedPreferences("taskState", MODE_PRIVATE);
		preference.edit().clear().commit();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(data!=null){
			grbaList=(List<grabList>) data.getSerializableExtra("grabList");
			adapter=new TaskSuperviseAdapter(grbaList, TaskSuperviseActivity.this);
			mListView.setAdapter(adapter);
			mSwipeLayout.setRefreshing(false);
		}
//		if(data!=null){
//			if(requestCode==0&&resultCode==0){
//				task=data.getStringExtra("caseNumber");
//			}else if(requestCode==1&&resultCode==1){
//				car=data.getStringExtra("targetCar");
//			}else if(requestCode==2&&resultCode==2){
//				state=data.getStringExtra("state");
//			}else if(requestCode==3&&resultCode==3){
//				sTime=data.getStringExtra("sTime");
//				eTime=data.getStringExtra("eTime");
//			}
//		}
//		dialog=ProgressDialog.show(this, null, "获取监管列表", false, false);
//		RequestTask requestTask=new RequestTask(deviceId, uuid, task, car, state, sTime, eTime);
//		new TaskSupervisionThread(TaskSuperviseActivity.this, handler, requestTask).start();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		order=grbaList.get(position);
		if(order.getCaseState().equals("1")){
			RequestOthers requestOthers=new RequestOthers(deviceId, uuid, order.getCaseNumber());
			new GetOtherThread(TaskSuperviseActivity.this, handler, requestOthers).start();
			dialog=ProgressDialog.show(this, null, "获取详细信息", false, false);

		}else{
			intent=new Intent(TaskSuperviseActivity.this, OrderDetailActivity.class);
			intent.putExtra("order", order);
			startActivity(intent);
		}

	}

}
